package initCenter

import (
	"sync"
)

var (
	// key:初始化成功的标志名称   val:占位符
	initSuccessMap = make(map[string]chan bool)
	mutex          sync.Mutex
)

// 等待初始化成功
func WaitInitSucc(chanName string) {
	var channel chan bool
	func() {
		mutex.Lock()
		defer mutex.Unlock()

		var exist bool
		channel, exist = initSuccessMap[chanName]
		if !exist {
			channel = make(chan bool, 1)
			initSuccessMap[chanName] = channel
		}
	}()

	// 等待初始化成功
	<-channel

	// 如果已经初始化成功，并且已经读取，再写入一条数据，保证其他地方读取
	channel <- true
}

// 通知初始化成功
func NotifyInitSuccess(chanName string) {
	var channel chan bool
	func() {
		mutex.Lock()
		defer mutex.Unlock()

		var exist bool
		channel, exist = initSuccessMap[chanName]
		if !exist {
			channel = make(chan bool, 1)
			initSuccessMap[chanName] = channel
		}
	}()

	// 初始化成功，向其中写入一条数据
	channel <- true
}
